<template>
  <view class="c-pd">
    <van-notice-bar left-icon="volume-o" text="报警须知：请勿虚假报警，否则将承担相应后果！" />
    <view class="mt-3">
      <SelectLocation :isGetUserAddress="true" @returnData="setLocation" @clearData="clearLocation" />
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="详细位置" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="dataForm.site"
              type="textarea"
              placeholder="请输入详细位置"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  dataForm.site = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <van-cell-group inset>
        <van-cell title="灾情描述" use-label-slot>
          <view slot="label">
            <van-field
              custom-style="border: 1px solid #ddd; border-radius:16rpx"
              :value="dataForm.fireDesc"
              type="textarea"
              placeholder="请描述具体情况"
              :border="false"
              :autosize="{ maxHeight: 200, minHeight: 100 }"
              @change="
                (e: any) => {
                  dataForm.fireDesc = e.detail;
                }
              "
            />
          </view>
        </van-cell>
      </van-cell-group>
    </view>
    <view class="mt-3">
      <UploadFile @clearUrl="clearUrl" @returnUrl="setVideoUrl" title="上传视频"></UploadFile>
    </view>
    <view class="mt-3" :style="{ marginBottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="handleSendReport">提交</van-button>
    </view>

    <van-dialog use-slot title="24小时内消防报警记录" showCancelButton confirm-button-text="继续报警" cancel-button-text="放弃报警" confirm-button-color="#fabc2a" :show="data.alarmShow" @confirm="handleDialogConfirm" @cancel="handleDialogClose">
      <view class="dialog_box">
        <van-cell-group v-for="(item, index) in data.alarmList" :key="index" inset custom-class="cell_box">
          <van-cell title="报警地址" :label="item.address" />
          <van-cell title="报警时间" :label="item.createDate" />
        </van-cell-group>
      </view>
    </van-dialog>
  </view>
</template>

<script setup lang="ts">
import HomeRequest from '@/request/homeRequest';
import UploadFile from '../component/UploadFile.vue';
import SelectLocation from '../component/SelectLocation.vue';
import useAppStore from '@/store/modules/app';
import { navigate } from '@/utils/navigate';
import useModal from '@/hooks/useModal';
import useToast from '@/hooks/useToast';

interface IData {
  beeperId: number;
  alarmList: IGetAlarmRecord[];
  alarmShow: boolean;
}

interface ILocation {
  buildId: number;
  buildName: string;
  floorId: number;
  floorName: string;
  unitId: number;
  unitName: string;
  houseNumber: string;
  houseNumberId: string;
}

interface IDataForm extends ILocation {
  fireDesc: string;
  fireVideos: string;
  site: string;
}

const store = useAppStore();

const { showModal } = useModal();

const { showToast } = useToast();

const data = reactive<IData>({
  beeperId: store.$state.beeperId,
  alarmList: [],
  alarmShow: false,
});

const dataForm = reactive<IDataForm>({
  buildId: 0,
  buildName: '',
  fireDesc: '',
  fireVideos: '',
  floorId: 0,
  floorName: '',
  site: '',
  unitId: 0,
  unitName: '',
  houseNumber: '',
  houseNumberId: '',
});

onLoad(() => {
  getAlarmRecord();
});

//清空视频
const clearUrl = () => {
  dataForm.fireVideos = '';
};

//获取视频地址
const setVideoUrl = ({ url }: { url: string }) => {
  dataForm.fireVideos = url;
};

//设置楼栋层
const setLocation = (payload: { item: IBuildingTreeRes[]; isUpload: boolean }) => {
  if (payload.item.length >= 1 && payload.item[0].id) {
    dataForm.buildId = Number(payload.item[0].id);
    dataForm.buildName = payload.item[0].name;
  }
  if (payload.item.length >= 2 && payload.item[1].id) {
    dataForm.unitId = Number(payload.item[1].id);
    dataForm.unitName = payload.item[1].name;
  }
  if (payload.item.length >= 3 && payload.item[2].id) {
    dataForm.floorId = Number(payload.item[2].id);
    dataForm.floorName = payload.item[2].name;
  }
  if (payload.item.length >= 4 && payload.item[3].id) {
    dataForm.houseNumberId = String(payload.item[3].id);
    dataForm.houseNumber = payload.item[3].name;
  }
  if (payload.isUpload) {
    getAddressAlarmRecord();
  }
};

//清空楼栋层
const clearLocation = () => {
  Object.assign(dataForm, {
    buildId: 0,
    buildName: '',
    unitId: 0,
    unitName: '',
    floorId: 0,
    floorName: '',
    houseNumberId: '',
    houseNumber: '',
  });
};

//获取报警记录
const getAlarmRecord = () => {
  let params: any = { hasLoading: true, beeperId: data.beeperId };
  HomeRequest.GetAlarmRecord(params).then((res) => {
    if (res.status === 0) {
      data.alarmList = res.data;
      if (data.alarmList.length > 0) {
        data.alarmShow = true;
      }
    }
  });
};

//当前楼栋层报警记录
const getAddressAlarmRecord = () => {
  HomeRequest.GetAddressAlarmRecord({
    buildId: dataForm.buildId,
    floorId: dataForm.floorId,
    houseNumberId: dataForm.houseNumberId,
    unitId: dataForm.unitId,
    hasLoading: true,
  }).then((res) => {
    if (res.status === 0) {
      if (res.data.length > 0) {
        dialogTip();
      }
    }
  });
};

const handleDialogConfirm = () => {
  data.alarmShow = false;
};

const handleDialogClose = () => {
  navigate({ url: '', type: 'navigateBack' });
};

//是否继续新增报警记录
const dialogTip = () => {
  showModal('已存在相同地址报警记录，是否继续新增?', {
    cancelText: '取消',
    confirmText: '继续',
    showCancel: true,
    success: (res) => {
      if (res.cancel) {
        navigate({ url: '', type: 'navigateBack' });
      }
    },
  });
};

//消防报警提交
const handleSendReport = () => {
  const { buildName, fireDesc, fireVideos, floorName, site, unitName, houseNumber } = dataForm;
  const residentAddress = buildName + unitName + floorName + houseNumber;

  if (residentAddress === '' && site === '') {
    showModal('所在楼层或详细位置必须填写一个');
    return false;
  }
  if (fireVideos === '' && fireDesc === '') {
    showModal('灾情描述或上传视频必须填写一个');
    return false;
  }
  const params = {
    beeperId: data.beeperId,
    hasLoading: true,
    ...dataForm,
    buildId: dataForm.buildId === 0 ? '' : dataForm.buildId,
    floorId: dataForm.floorId === 0 ? '' : dataForm.floorId,
    unitId: dataForm.unitId === 0 ? '' : dataForm.unitId,
  };

  HomeRequest.SubmitAlarmOrder(params)
    .then((res) => {
      if (res.status === 0) {
        showToast('提交成功', 'success');
        setTimeout(() => {
          navigate({ url: '', type: 'navigateBack' });
        }, 800);
      }
    })
    .catch((err) => {
      showToast(err.msg || '提交失败');
    });
};
</script>

<style lang="scss" scoped>
:deep(.van-panel) {
  border-radius: 16rpx !important;
}

.dialog_box {
  overflow: auto;
  padding: 24rpx 24rpx 0;
  max-height: 800rpx;
  background: #f3f3f3;
}

:deep(.van-cell-group) {
  margin-bottom: 24rpx !important;
}

:deep(.van-dialog__header) {
  padding-top: 24rpx;
  padding-bottom: 24rpx;
}
</style>
